"""
动作组管理器模块

该模块负责动作组的加载、管理和执行。
"""

import os
import json
import logging
from typing import Dict, List, Optional
from robot_core.protocols.servo_protocol import ServoProtocol


class ActionManager:
    """动作组管理器类"""

    def __init__(
        self,
        protocol: ServoProtocol,
        action_dir: str = "actions",
        log_level: int = logging.INFO,
    ):
        """
        初始化动作组管理器

        Args:
            protocol: 舵机协议实例
            action_dir: 动作组文件目录
            log_level: 日志级别
        """
        # 配置日志
        logging.basicConfig(level=log_level)
        self.logger = logging.getLogger(__name__)

        self.protocol = protocol
        self.action_dir = action_dir
        self.actions: Dict[str, dict] = {}  # 动作组缓存
        self._load_actions()

    def _load_actions(self) -> None:
        """加载所有动作组文件"""
        try:
            if not os.path.exists(self.action_dir):
                os.makedirs(self.action_dir)
                self.logger.info(f"创建动作组目录: {self.action_dir}")
                return

            for filename in os.listdir(self.action_dir):
                if filename.endswith(".json"):
                    action_name = os.path.splitext(filename)[0]
                    with open(os.path.join(self.action_dir, filename), "r") as f:
                        self.actions[action_name] = json.load(f)
                    self.logger.info(f"加载动作组: {action_name}")
        except Exception as e:
            self.logger.error(f"加载动作组时出错: {e}")

    def get_action(self, action_name: str) -> Optional[dict]:
        """
        获取动作组

        Args:
            action_name: 动作组名称

        Returns:
            Optional[dict]: 动作组数据，如果不存在则返回None
        """
        return self.actions.get(action_name)

    def save_action(self, action_name: str, action_data: dict) -> bool:
        """
        保存动作组

        Args:
            action_name: 动作组名称
            action_data: 动作组数据

        Returns:
            bool: 是否保存成功
        """
        try:
            with open(os.path.join(self.action_dir, f"{action_name}.json"), "w") as f:
                json.dump(action_data, f, indent=2)
            self.actions[action_name] = action_data
            self.logger.info(f"保存动作组: {action_name}")
            return True
        except Exception as e:
            self.logger.error(f"保存动作组时出错: {e}")
            return False

    def delete_action(self, action_name: str) -> bool:
        """
        删除动作组

        Args:
            action_name: 动作组名称

        Returns:
            bool: 是否删除成功
        """
        try:
            file_path = os.path.join(self.action_dir, f"{action_name}.json")
            if os.path.exists(file_path):
                os.remove(file_path)
                if action_name in self.actions:
                    del self.actions[action_name]
                self.logger.info(f"删除动作组: {action_name}")
                return True
            return False
        except Exception as e:
            self.logger.error(f"删除动作组时出错: {e}")
            return False

    def list_actions(self) -> List[str]:
        """
        获取所有动作组名称

        Returns:
            List[str]: 动作组名称列表
        """
        return list(self.actions.keys())
